// 引入接口文件
import {regionArea,getZituoDailyData,verifyCodeFun,getTeamsByProjectId,getTeamUser,importExcel} from './talkIndicatorsServ.js'

// 对象和JSON字符串互转
import { parse } from 'qs'
// 弹出消息框
import { message } from 'antd'
import axios from 'axios'
import config from 'config/config'
// 日期处理对象
import moment from 'moment'
/* isEmpty 对象是否为空
 * isArray 对象是否数组
 * cloneDeep 对象深拷贝
 */
import {isEmpty, isArray, cloneDeep, merge} from 'lodash'

const queryList = [
  {
    name: '区域', type: 'mulSelect', key: 'areaId', value: '', notNeedAll: true, list: []
  },
  {
    name: '项目', type: 'mulSelect', key: 'projectId', value: '', notNeedAll: true, list:[]
  },
  {
    name: '团队', type: 'mulSelect', key: 'teamId', value: '', notNeedAll: true, list: []
  },
  {
    name: '姓名', type: 'text', key: 'userName', value: '', 
  },
  {
    name: '统计时间', type: 'monthOne', key:'month', value: '', 
  },
]


// 初始默认状态
const defultState = {
  loading: false,
  biz: {
		queryForm: {}
  },
  queryList,
  areaId:'',
  projectId:'',
  products:[],
  areaList:[],
  teamList: [],
  dataList: [],
  detailData: {
    pageNo: 1,
    pageSize: 10
  },//详情数据
}



// 声明module
const tmpModule = {
  namespace: 'messageListModel',
  state: cloneDeep(defultState),
  subscriptions: {
    setup ({dispatch, history}) {
      history.listen(({ pathname, query }) => {
        if('' + tmpModule.pathname === '' + pathname){
          dispatch({ type: 'regionArea', payload:{}});
          dispatch({ type: 'updateStore', payload: cloneDeep(defultState) });
        }
      })
    },
  },
  // 方法列表
  effects: {
     //获取区域项目
    *regionArea({payload},{put,select,call}){
      let {areaList,queryList} = yield select(state => state[tmpModule.namespace])
      let params = {
          level : 2 
        }
      if(yield call(verifyCodeFun,{})){
       const { data } = yield call(regionArea, {...params})
        let list = data
        if(!list.length){
          return
        }
        areaList =  list.map((item,index)=>{
          return {
            name: item.buname,
            id: item.buguid,
            children: item.childSysUninessunitList
          }
        })
        queryList[0].list = areaList
        yield put({type: 'updateStore', payload: {areaList,queryList}})
      }
    },

  *getTeamsByProjectId({payload},{put,select,call}){
      let {teamList,queryList} = yield select(state => state[tmpModule.namespace])
      let params = {
        projectId:payload.projectId,
      }
      const { success,rows } = yield call(getTeamsByProjectId, {...params})
      if(success){
        teamList = rows
        if(!rows.length){
          return
        }
        teamList =  rows.map((item,index)=>{
          return {
            name: item.team_name,
            id: item.id,
          }
        })
        queryList[2].list = teamList
        yield put({type: 'updateStore', payload: {teamList,queryList}})
      }
  },
  *exportList({payload},{put,select,call}){
    let {projectId,queryList} = yield select(state => state[tmpModule.namespace])
    if(!queryList[0].value.length){
      message.warn('请选择区域')
      return
    }
    if(!projectId){
      message.warn('请选择项目')
      return
    }
    let params = {};
    params['areaId'] = queryList[0].value.length?queryList[0].value.join(','):''
    params['projectId'] = projectId?projectId:''
    params['teamList'] = queryList[2].value?queryList[2].value:[]
    params['userName'] = queryList[3].value?queryList[3].value: ''
    params['month'] = queryList[4].value[0]?queryList[4].value[0]:''
    axios({
        method: 'post',
        url: config.baseUrl+`zituo-admin/a/target/excelData`,
        responseType: 'blob',
        headers: {},
        data: params,
    }).then(res => {
        const content = res.data
        const blob = new Blob([content])
        Date.prototype.Format = function (fmt) { // author: meizz
            var o = {
                "M+": this.getMonth() + 1, // 月份
                "d+": this.getDate(), // 日
                "h+": this.getHours(), // 小时
                "m+": this.getMinutes(), // 分
                "s+": this.getSeconds(), // 秒
                "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
                "S": this.getMilliseconds() // 毫秒
            };
            if (/(y+)/.test(fmt))
                fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
            for (var k in o)
                if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                    return fmt;
        }
        let dateTime = new Date().Format("yyyy-MM-dd hh:mm:ss");
        let fileName = `指标完成情况报表 ${dateTime}.xls`
        if ('download' in document.createElement('a')) { // 非IE下载
          const elink = document.createElement('a')
          elink.download = fileName
          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob)
          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href) // 释放URL 对象
          document.body.removeChild(elink)
        } else { // IE10+下载
          navigator.msSaveBlob(blob, fileName)
        }
        message.success('导出成功')
    })
  },
  //查询操作
  *search({ payload = {} }, { call, put, select }) {
    let {projectId,queryList,dataList,detailData} = yield select(state => state[tmpModule.namespace])
    //组装接口入参
    if(!queryList[0].value.length){
      message.warn('请选择区域')
      return
    }
    if(!projectId){
      message.warn('请选择项目')
      return
    }
    if(!queryList[4].value[0]){
      message.warn('请选择时间')
      return
    }
    let params = {};
    params['areaId'] = queryList[0].value.length?queryList[0].value.join(','):''
    params['projectId'] = projectId?projectId:''
    params['teamList'] = queryList[2].value?queryList[2].value:[]
    params['userName'] = queryList[3].value?queryList[3].value: ''
    params['month'] = queryList[4].value[0]?queryList[4].value[0]:''
    params['pageNo'] = detailData.pageNo
    params['pageSize'] = detailData.pageSize
    yield put({type: 'updateStore', payload: {loading: true}})
    const { success,pageNo,pageSize,total,rows,message} = yield call(getZituoDailyData, {...params})
    if(message){
      yield put({type: 'updateStore', payload: {loading: false}}) 
    }
    if(success){
      detailData['pageNo'] = pageNo
      detailData['pageSize'] = pageSize
      detailData['total'] = total
      if(rows.length){
        for(var i=0;i<rows.length;i++){
          rows[i].ruleNo = i+1
        }
      }
      dataList = rows
      yield put({type: 'updateStore', payload: {loading: false,dataList,detailData}}) 
    }
  },
  // 查询条件重置
  *queryReset({ }, { call, put, select }) {
    let { areaList} = yield select(state => state[tmpModule.namespace])
    let newQueryList = cloneDeep(queryList)
    newQueryList[0].list = areaList
    yield put({ type: 'updateStore', payload: { queryList:newQueryList} });
  },

   //改变查询条件
   *inputChange({ payload }, { call, put, select }) {
    let { areaId,projectId,queryList} = yield select(state => state[tmpModule.namespace])
    const { key, value } = payload;
    let data = queryList.find(item => item.key === key);

    if(data.key == 'areaId'){
      yield put({type: 'filterProjectList', payload:{areaId:value}})
      areaId = value
      yield put({ type: 'updateStore', payload: { areaId } });

    }else if(data.key == 'projectId'){
      if(queryList[1].list.length){
        let ids = value.join(',')
        yield put({type: 'getTeamsByProjectId', payload:{projectId:ids}})
        projectId = ids
        yield put({ type: 'updateStore', payload: { projectId } });
      }

    }else if(data.key == 'times'){

      queryList[4].value = value
      yield put({ type: 'updateStore', payload: { queryList } });
    }

    data.value = value;
    //刷新列表参数
    yield put({ type: 'updateStore', payload: { queryList: [...queryList, ...data] } });
  },

  *filterProjectList({payload},{put,select,call}){    
    let {products,areaList,queryList} = yield select(state => state[tmpModule.namespace])
    let list = []
    for(var item of areaList){
      for(var itemed of payload.areaId){
        if(itemed&&item.id == itemed){
          list.push(...item.children)
        }
      }
    }
    if(list.length){
      products =  list.map((item,index)=>{
        return {
          name: item.buname,
          id: item.buguid,
        }
      })
    }
    queryList[1].list = products
    yield put({type: 'updateStore', payload: {products,queryList}})
  },
  },
  
  // 存入状态机
  reducers: {
    updateStore(preState, action) {
      return { ...preState, ...action.payload };
    }
  }
}

export default tmpModule
